import cv2 as cv


cap = cv.VideoCapture("/Users/apple/Desktop/data/vtest.avi")
mog = cv.createBackgroundSubtractorMOG2()
ret, frame = cap.read()


# 遍历视频每一帧
while ret:

    # 预处理：缩小当前帧，提取掩膜、前景、背景
    frame = cv.pyrDown(frame)
    fgmask = mog.apply(frame)
    foreGround = frame & cv.cvtColor(fgmask, cv.COLOR_GRAY2BGR)
    backGround = mog.getBackgroundImage(frame.copy())


    # 处理掩膜：高斯降噪、二值化
    # fgmask = cv.GaussianBlur(fgmask, (3, 3), 0)
    r, th = cv.threshold(fgmask, 244, 255, cv.THRESH_BINARY)


    # 画矩形并计数
    count = 0
    image, contours, hierarchy = cv.findContours(th, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    for c in contours:
        if cv.contourArea(c) > 60:
            count += 1
            (x, y, w, h) = cv.boundingRect(c)
            cv.rectangle(frame, (x, y), (x+w, y+h), (255, 255, 0), 2)
            cv.putText(frame, str(count), (x, y), cv.FONT_HERSHEY_COMPLEX, 0.4, (0, 255, 0), 1)


    cv.imshow("1 - Video Detection", frame)
    cv.imshow("2 - Frame Fgmask", th)
    cv.imshow("3 - Diff Foreground", foreGround)
    cv.imshow("4 - Background", backGround)

    # 下一帧读取
    ret, frame = cap.read()

    # 按esc退出
    if cv.waitKey(10) & 0xff == 27:
        break


cap.release()
cv.destroyAllWindows()
